package com.kungfuhacking.wristbandpro.base.presenter;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.kungfuhacking.wristbandpro.base.view.IHomeView;
import com.kungfuhacking.wristbandpro.database.DatabaseManager;
import com.kungfuhacking.wristbandpro.location.presenter.LocationPresenter;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Aaron on 17/3/30.
 */

public class IHomePresenter extends LocationPresenter implements BasePresenter {

    private IHomeView iHomeView;
//    private BaseView iBaseView;

    public IHomePresenter(IHomeView iHomeView) {
        this.iHomeView = iHomeView;
    }

//    public IHomePresenter(BaseView iBaseView) {
//        this.iBaseView = iBaseView;
//    }

    @Override
    public void clearRequest() {
        compositeDisposable.clear();
    }

    private long mPressedTime = 0;

    public void exitApp() {

        long mNowTime = System.currentTimeMillis();//获取第一次按键时间

        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差

            iHomeView.showErr("再按一次退出程序");

            mPressedTime = mNowTime;

        } else {//退出程序

            EventBus.getDefault().post(Constant.EXIT_APP);
            iHomeView.finishActivity();
            System.exit(0);

        }
    }


    public void handleMessage(String msb) {

        if (MqttConstant.UPDATE_RED_COUNT.equals(msb))
            setRedCount();
    }


    private String TAG = getClass().getSimpleName();

    // 设置红点个数
    public void setRedCount() {

        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {

                Log.d(TAG, " 查询未读条数线程 : " + Thread.currentThread().getName());
                e.onNext(DatabaseManager.getInstance().queryAllUnReadCount(iHomeView.getContex(), iHomeView.getSp().getString(MqttConstant.USERID, "")));

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Integer sum) {
                        Log.d(TAG, "消息条数 : " + sum);

                        if (sum == -100)
                            return;

                        iHomeView.setUnredBackground(sum < 99);
                        iHomeView.setUnredCount(sum > 99 ? "99+" : (sum + ""));
                        iHomeView.setRedVisible(sum > 0);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "查询未读消息出错: " + e.getLocalizedMessage() + ", " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 极光推送设置alias
     *
     * @param phone 手机号
     */
    public void setAlias(String phone) {
        if (TextUtils.isEmpty(phone)) {
            String logs = "phone is empty";
            LogUtil.e("TAG", logs);
            return;
        }
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, phone));
    }

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtil.e("TAG", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(iHomeView.getContex(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    LogUtil.e("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtil.e("TAG", logs);

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.e("TAG", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtil.e("TAG", logs);
            }

        }
    };
}
